<template>
  <div class="order-list">
    <!-- 搜索和操作栏 -->
    <div class="operation-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号">
          <el-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待付款" :value="0" />
            <el-option label="待发货" :value="1" />
            <el-option label="待收货" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <el-card class="list-card">
      <el-table
        :data="orderList"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column label="收货信息" min-width="220">
          <template #default="{ row }">
            {{ formatAddress(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">查看详情</el-button>
            <el-button v-if="row.status === 1" type="success" link @click="handleShip(row)">发货</el-button>
            <el-button v-if="row.status === 0" type="danger" link @click="handleCancel(row)">取消订单</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="shipForm.company" placeholder="请选择物流公司">
            <el-option label="顺丰速运" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="shipForm.trackingNo" placeholder="请输入物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="shipLoading">
            确认发货
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllOrderList, jiangShipOrder, jiangCancelOrder } from '@/api/order'

const router = useRouter()
const loading = ref(false)
const shipDialogVisible = ref(false)
const shipLoading = ref(false)
const shipFormRef = ref(null)
const currentShipOrder = ref(null)

// 搜索表单
const searchForm = ref({
  orderNo: '',
  status: '',
  timeRange: []
})

// 发货表单
const shipForm = ref({
  company: '',
  trackingNo: ''
})

// 发货表单验证规则
const shipRules = {
  company: [
    { required: true, message: '请选择物流公司', trigger: 'change' }
  ],
  trackingNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
}

// 订单列表
const orderList = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化地址
const formatAddress = (row) => {
  if (!row) return '无'
  return `${row.province || ''}${row.city || ''}${row.district || ''}${row.addressDetail || ''}（${row.recipientName || ''} ${row.recipientPhone || ''}）`
}

// 格式化支付方式
const formatPaymentMethod = (method) => {
  const methods = {
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付',
    'BANK': '银行卡'
  }
  return methods[method] || method
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '已完成',
    4: '已取消'
  }
  return texts[status] || '未知'
}

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  try {
    const res = await getAllOrderList()
    orderList.value = res
    total.value = res.length
  } catch (error) {
    console.error('加载订单列表失败：', error)
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadOrderList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    orderNo: '',
    status: '',
    timeRange: []
  }
  handleSearch()
}

// 查看订单详情
const handleViewDetail = (row) => {
  router.push(`/jiang/orders/${row.id}`)
}

// 发货
const handleShip = (row) => {
  currentShipOrder.value = row
  shipForm.value = {
    company: '',
    trackingNo: ''
  }
  shipDialogVisible.value = true
}

// 确认发货
const confirmShip = async () => {
  if (!shipFormRef.value) return
  
  try {
    await shipFormRef.value.validate()
    
    shipLoading.value = true
    await jiangShipOrder(currentShipOrder.value.id, shipForm.value)
    
    ElMessage.success('发货成功')
    shipDialogVisible.value = false
    loadOrderList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('发货失败：', error)
    ElMessage.error('发货失败，请重试')
  } finally {
    shipLoading.value = false
  }
}

// 取消订单
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await jiangCancelOrder(row.id)
    ElMessage.success('订单已取消')
    loadOrderList()
  } catch (error) {
    if (error === 'cancel') return
    console.error('取消订单失败：', error)
    ElMessage.error('取消订单失败，请重试')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrderList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrderList()
}

onMounted(() => {
  loadOrderList()
})
</script>

<style lang="scss" scoped>
.order-list {
  .operation-bar {
    margin-bottom: 20px;
  }

  .list-card {
    .goods-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .goods-image {
        width: 60px;
        height: 60px;
        border-radius: 4px;
      }

      .goods-detail {
        .goods-name {
          margin-bottom: 4px;
          color: var(--el-text-color-primary);
        }

        .goods-price {
          color: var(--el-text-color-secondary);
          font-size: 13px;
        }
      }
    }

    .order-detail {
      padding: 20px;
      background-color: var(--el-fill-color-light);

      .detail-item {
        margin-bottom: 12px;
        font-size: 14px;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          color: var(--el-text-color-secondary);
          margin-right: 8px;
        }

        .value {
          color: var(--el-text-color-primary);
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
